package com.citycloud.rpc.framework.protocol.http;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

public class HttpServer {
    // tomcat,jetty

    public void start(String hostname, Integer port) {


        //todo 1,得到tomcat里的Service
        Tomcat tomcat = new Tomcat();
        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

        //todo 2,构建Servlet容器
        //一级容器Servlet
        Engine engine = new StandardEngine();
        engine.setDefaultHost(hostname);
        //二级容器Servlet
        Host host = new StandardHost();
        host.setName(hostname);
        engine.addChild(host);
        //三级容器Servlet
        Context context = new StandardContext();
        String contextPath = "";
        context.setPath(contextPath);//contextPath
        context.addLifecycleListener(new Tomcat.FixContextListener());//todo 非常重要不能省略
        host.addChild(context);

        //todo 3,service关联Servlet容器
        service.setContainer(engine);//关联容器

        //todo 4,构建连接,设置监听端口
        Connector connector = new Connector();
        connector.setPort(port);

        //todo 5,service关联Connector连接
        service.addConnector(connector);//关联连接

        //todo 6,注册Servlet
        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet());
        //todo 6,设置Servlet映射路径
        context.addServletMappingDecoded("/*", "dispatcher");


        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }


    }


    //todo  add by liyi
    public static void main(String[] args) {
        Tomcat tomcat = new Tomcat();
        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");
        Engine engine = new StandardEngine();
        service.setContainer(engine);
        Connector connector = new Connector();
        connector.setPort(8080);
        service.addConnector(connector);

        Host host = new StandardHost();
        host.setName("localhost");
        engine.addChild(host);

        Context context = new StandardContext();
        context.setPath("");
        context.addLifecycleListener(new Tomcat.FixContextListener());
        host.addChild(context);

        tomcat.addServlet("", "dispatcher", new DispatcherServlet());
        context.addServletMappingDecoded("/*", "dispatcher");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}
